<template>

    <el-dialog  v-loading="loading" v-model="props.dialogVisible" :title="tipTitle" width="800" :before-close="handleClose">
 
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80" class="ruleForm">

{{ ruleForm }}
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="头像">
                        <!-- <el-upload class="avatar-uploader" :action="BASE_UPLOAD_URL + '/upload/add'"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :headers="headers"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="ruleForm.photo" :src="BASE_IMG_URL+ruleForm.photo" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload> -->

                        <UploadFile v-model="ruleForm.photo"></UploadFile>

                    </el-form-item>
                    <el-form-item label="楼栋">

                        <CascaderBuilding @change="handleBuildChange" v-model="houseParams.buildingid" type="single"></CascaderBuilding>

        
                  <!-- <el-cascader
                v-model="houseParams.buildingid"
      :options="buildingList"
      :props="buildingProps"
      @change="handleBuildChange"
    /> -->

                    </el-form-item>
                    <el-form-item label="房间">
                   
                      <el-select v-model="ruleForm.houseid" placeholder="请选择居民类型" style="width:150px">
    <el-option
      v-for="item in houseList"
      :key="item.id"
      :label="item.houseno"
      :value="item.id"
    />
  </el-select>

                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="ruleForm.name" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="ruleForm.sex" >
      <el-radio :value="1" size="large">男</el-radio>
      <el-radio :value="0" size="large">女</el-radio>
    </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="民族">
                        <el-input  v-model="ruleForm.nation" />
                    </el-form-item>
                    <el-form-item label="籍贯">
                        <el-input  v-model="ruleForm.usernative" />
                    </el-form-item>
                    <el-form-item label="证件">
                        <el-input  v-model="ruleForm.cardid" />
                    </el-form-item>
                    <el-form-item label="电话"  prop="mobile">
                        <el-input   v-model="ruleForm.mobile" />
                    </el-form-item>
                    <el-form-item label="类型" prop="usertype">
                        <el-select v-model="ruleForm.usertype" placeholder="请选择居民类型" style="width:150px">
    <el-option
      v-for="item in userTypes"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">返回</el-button>
                <el-button @click="submit(ruleFormRef)" type="primary">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script setup lang='ts'>
import { UserInfo, UserInfoType } from '@/apis/userinfo/type';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { ref, defineProps, defineEmits, computed, reactive, onMounted } from 'vue';
// import { Plus } from '@element-plus/icons-vue'
import { addUserinfo, getUserinfoById, getUserinfoType } from '@/apis/userinfo/userinfo';
import { getBuildingList, getHouseList } from '@/apis/building/building';
import { BuildingNode, HouseItem, HouseParams } from '@/apis/building/type';
import UploadFile from '@/components/upload/UploadFile.vue';
const emit = defineEmits(['close']);

const tipTitle = computed(() => props.id ? '修改' : '添加');
// const BASE_UPLOAD_URL = import.meta.env.VITE_BASE_URL;
// const BASE_IMG_URL = import.meta.env.VITE_IMG_URL;

// const headers= { Authorization: sessionStorage.getItem('token')};


interface Props {
    id: number,
    buildingid:number,
    dialogVisible: boolean
}

const props = withDefaults(defineProps<Props>(), {
    id: 0,
    buildingid:0,
    dialogVisible: false

})
const ruleFormRef = ref<FormInstance>()
//表单数据

const loading = ref(false)
let ruleForm = reactive<UserInfo>({
    id: props.id,
    photo: '',
    houseid: undefined,
    name: '',
    sex: undefined,
    nation: '',
    usernative: '',
    cardid: '',
    mobile: '',
    usertype: undefined,

});
const validateMobile=(rule: any, value: any, callback: any)=>{

    const regex = /^1[2-9]\d{9}$/;

    if(value===""){
        callback(new Error('请输入手机号')) //校验失败
    }
    else if(!regex.test(value)){
        callback(new Error('手机号格式不正确'))
    }
    else{
        callback(); //校验通过
    }
 
}
const rules = reactive<FormRules<UserInfo>>({
    photo: [
        { required: true, message: '请上传头像', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'change' },
    ],
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validateMobile, trigger: 'blur' },
    ],
    usertype: [
        { required: true, message: '请选择居民类型', trigger: 'change' },
    ],
    
})

//文件上传
// const handleAvatarSuccess: UploadProps['onSuccess'] = (
//     response,
//     uploadFile
// ) => {
//     console.log("上传成功", response);

//     if(response.errCode==10000){
//         ruleForm.photo = response.data;
//     }

// }

//获取居民类型
const userTypes=ref<UserInfoType[]>([]);

const getUserTypeData=async ()=>{

    const res=await getUserinfoType();

    userTypes.value=res.data.list;

}
getUserTypeData();


//获取楼栋信息

// const buildingProps={
//     label: 'name',
//     value: 'id',
// }
// const selectedBuilding=ref(0);
// const buildingList=ref<BuildingNode[]>([]);
// const getBuildingData=async ()=>{

//     const res=await getBuildingList();

//     buildingList.value=res.data.list;

// }
// getBuildingData();

//获取房间
const houseParams=reactive<HouseParams>({
    buildingid:props.buildingid,
    page:1,
    psize:1000,
}
)
const houseList=ref<HouseItem[]>([]);

const getHouseData=async ()=>{

    const res=await getHouseList(houseParams);

    houseList.value=res.data.list;

}


const handleBuildChange=(e:number[])=>{
    console.log("handleBuildChange",e);
    
    // if(!e){
    //     houseParams.buildingid=0;
    //     return
    // }
    // houseParams.buildingid=e[e.length-1];

    ruleForm.houseid=undefined;

    getHouseData();

}


// const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
//     let imgType = ['image/jpeg', 'image/gif', 'image/jpg', 'image/png', 'image/bmp'];


//     if (!imgType.includes(rawFile.type)) {
//         ElMessage.error('请选择图片!')
//         return false
//     } else if (rawFile.size / 1024 / 1024 > 5) {
//         ElMessage.error('图片大小不能超过5MB!')
//         return false
//     }
//     return true
// }

//  const dialogVisible = ref(props.dialogShow);
const handleClose = (done: () => void) => {
    emit("close");
}

//表单提交
const postData=async ()=>{
    loading.value=true
    const res=await addUserinfo(ruleForm).catch(() => undefined);
    loading.value=false;
    if(!res) return;
    emit("close",true);
}
const submit = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        if (valid) {

            postData();

        }
    })

}

onMounted(async () => {
    
    if(ruleForm.id){
      const res=await  getUserinfoById(ruleForm.id).catch(err=>undefined);
      if(!res) return;

      Object.assign(ruleForm,res.data);
      getHouseData();
    }

})
</script>
<style scoped lang='less'>
.ruleForm {
    width: 100%;
    box-sizing: border-box;
    padding: 0px 60px 0px 30px;

}

.avatar-uploader {
    width: 60px;
    height: 60px;
 
    .avatar {
        width: 100%;
        height: 100%;
        display: block;
    }
    :deep .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
        height: 100%;
}
    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100%;
        height: 100%;
        text-align: center;
    }
}
</style>